<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Bookcase;
use App\Models\BookcaseExhibition;
use App\Models\Exhibition;
use App\Models\ExhibitionProduction;
use App\Models\Manage;
use App\Validate\ExhibitionValidate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 展览管理
 */
class ExhibitionController extends CommonController
{
    public $exhibitionModelObj = null;
    public $validateObj = null;

    public function __construct()
    {
        parent::__construct();

        $this->validateObj = new ExhibitionValidate();
        $this->exhibitionModelObj = new Exhibition();
    }

    /**
     * 展览列表
     * @param keyword 关键字搜索
     * @param page 页数    默认第一页
     * @param limit 限制条数   默认 10 条
     * @param start_time 开始时间
     * @param end_time 结束时间
     * @param bookcase_id 机柜id 空 或 0 表示全部
     */
    public function exhibitionList()
    {
        $keyword = $this->request->input('keyword', '');
        $start_time = $this->request->input('start_time', '');
        $end_time = $this->request->input('end_time', '');
        $limit = $this->request->input('limit', 10);
        $page = $this->request->input('page', 10);
        $bookcase_id = $this->request->input('bookcase_id', '0');
        if (!empty($bookcase_id)) {
            //获取这个机柜对应的展览
            $bookcaseExhibitionModelObj =  new BookcaseExhibition();

            $exhibition_ids = $bookcaseExhibitionModelObj->getExhibitionIdByBookcaseId($bookcase_id);
        } else {
            $exhibition_ids = [];
        }

        $res = $this->exhibitionModelObj->select(['id', 'name', 'address', 'type_name', 'roll_speed', 'page_stay_min_time', 'start_time', 'end_time', 'status', 'create_time', 'manage_id'])
            ->with(['productions' => function ($query) {
                $query->select('pro_name');
            }, 'bookcases' => function ($query) {
                $query->select('name', 'stack_number');
            }])
            ->where(function ($query) use ($keyword, $bookcase_id, $exhibition_ids) {
                if ($keyword) {
                    $query->where('name', 'like', '%' . $keyword . '%');
                }
                if ($bookcase_id) {
                    $query->whereIn('id', $exhibition_ids);
                }
            })
            ->where(function ($query) use ( $start_time, $end_time) {
                if (!empty($start_time) && !empty($end_time)) {
                    $query->orWhereBetween('start_time', [$start_time, $end_time])->orWhereBetween('end_time', [$start_time, $end_time]);
                }
            })
            ->where('is_del', 1)
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();

        if ($res['data']) {
            $res = $this->disPageData($res);
            foreach ($res['data'] as $key => $val) {
                $res['data'][$key]['production_number'] = count($val['productions']);     //计算作品数量
                $bookcases = array_column($val['bookcases'], 'stack_number');     //获取柜子编号
                $res['data'][$key]['bookcase_stack_number'] = join(',', $bookcases);

                unset($res['data'][$key]['productions'], $res['data'][$key]['bookcases']);

                if ($val['manage_id']) {
                    $manageModelObj = new Manage();
                    $res['data'][$key]['manage_name'] = $manageModelObj->getManageNameByManageId($val['manage_id']);
                } else {
                    $res['data'][$key]['manage_name'] = null;
                }
            }

            //增加序号
            $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);

            return $this->returnApi(200, '获取成功', true, $res);
        }

        return $this->returnApi(203, '暂无数据');
    }


    /**
     * 展览列表（用于 书柜 筛选）
     * @param keyword 筛选条件
     * @param bookcase_id 书柜id  （用于判断此书柜是否已经显示某展览）
     */
    public function exhibitionFilterList()
    {
        $keyword = $this->request->input('keyword', '');
        $bookcase_id = $this->request->input('bookcase_id', '');
        $res = $this->exhibitionModelObj->select(['id', 'name'])
            ->where(function ($query) use ($keyword) {
                if ($keyword) {
                    $query->where('name', 'like', '%' . $keyword . '%');
                }
            })
            ->where('is_del', 1)
            ->orderByDesc('id')
            ->get();

        if ($res) {
            //获取书柜对应的所有的展览id
            $bookcaseExhibitionModelObj = new BookcaseExhibition();
            $exhibition_ids = $bookcaseExhibitionModelObj->getExhibitionIdByBookcaseId($bookcase_id);
            foreach ($res as $key => $val) {
                if ($bookcase_id) {
                    //判断是否选择
                    if (in_array($val['id'], $exhibition_ids)) {
                        $res[$key]['selected'] = true;
                    } else {
                        $res[$key]['selected'] = false;
                    }
                } else {
                    $res[$key]['selected'] = false;
                }
            }

            return $this->returnApi(200, '获取成功', true, $res);
        }


        return $this->returnApi(203, '暂无数据');
    }

    /**
     * 展览详情
     * @param id 展览id
     */
    public function exhibitionInfo()
    {
        //增加验证场景进行验证
        if (!$this->validateObj->scene('exhibition_info')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validateObj->getError());
        }
        $res = $this->exhibitionModelObj
            // ->select(['id', 'name', 'cab_code', 'stack_number', 'address', 'intro', 'is_config', 'create_time'])
            ->with([
                'foreword' => function ($query) {
                    $query->select('id', 'name', 'intro', 'intro_en', 'img', 'img_thumb');
                }, 'bookcases:id,name,stack_number'
                //  =>function($query){
                //      $query->select('Bookcase.id','name');
                //  }
                , 'productions' => function ($query) {
                    $query->select('pro_name');
                }
            ])
            ->where('is_del', 1)
            ->find($this->request->id);
        if (empty($res)) {
            return $this->returnApi(202, '获取失败');
        }


        //作品数量
        $res['production_number'] = count($res['productions']);     //计算作品数量
        unset($res['productions']);

        if ($res['manage_id']) {
            $manageModelObj = new Manage();
            $res['manage_name'] = $manageModelObj->getManageNameByManageId($res['manage_id']);
        } else {
            $res['manage_name'] = null;
        }

        return $this->returnApi(200, '获取成功', true, $res);
    }

    /**
     * 选择展览类型
     * @param keyword 关键字
     */
    public function getExhibitionTypeList()
    {
        $keyword = $this->request->input('keyword', '');
        $res = $this->exhibitionModelObj->select('id','type_name')->where(function ($query) use ($keyword) {
            if ($keyword) {
                $query->where('type_name','like','%' . $keyword . '%');
            }
        })->whereNotNull('type_name')
            ->orderByDesc('id')
            ->groupBy('type_name')
            ->get();

        if ($res) {
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(202, '获取失败');
    }

    /**
     * 选择展览地址
     * @param keyword 关键字
     */
    public function getExhibitionAddressList()
    {
        $keyword = $this->request->input('keyword', '');
        $res = $this->exhibitionModelObj->select('id','address')->where(function ($query) use ($keyword) {
            if ($keyword) {
                $query->where('address','like', '%' . $keyword . '%');
            }
        })->whereNotNull('address')
            ->orderByDesc('id')
            ->groupBy('address')
            ->get();
        if ($res) {
            return $this->returnApi(200, '获取成功', true, $res);
        }
        return $this->returnApi(202, '获取失败');
    }

    /**
     * 展览 配置 作品
     * @param id 展览id
     * @param production_id 作品id （所有的作品id） 多个 逗号 分隔     空表示清空 作品
     */
    public function exhibitionConfigProduction()
    {
        //增加验证场景进行验证
        if (!$this->validateObj->scene('exhibition_config_production')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validateObj->getError());
        }

        $production_id = $this->request->production_id;

        $res = $this->exhibitionModelObj->where('is_del', 1)->find($this->request->id);
        if (empty($res)) {
            return $this->returnApi(202, '配置失败');
        }

        DB::beginTransaction();
        try {
            $exhibitionProductionModelObj = new ExhibitionProduction();
            $exhibitionProductionModelObj->exhibitionProductionChange($res->id, $production_id, 'change');

            DB::commit();
            return $this->returnApi(200, '配置成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '配置失败');
        }
    }

    /**
     * 展览 删除 作品
     * @param id 展览id
     * @param production_id 作品id （只传删除的） 多个 逗号 分隔  
     */
    public function exhibitionDelProduction()
    {
        //增加验证场景进行验证
        if (!$this->validateObj->scene('exhibition_del_production')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validateObj->getError());
        }

        $production_id = $this->request->production_id;

        $res = $this->exhibitionModelObj->where('is_del', 1)->find($this->request->id);
        if (empty($res)) {
            return $this->returnApi(202, '删除失败');
        }

        DB::beginTransaction();
        try {
            $exhibitionProductionModelObj = new ExhibitionProduction();
            $exhibitionProductionModelObj->exhibitionProductionDel($this->request->id, $production_id);

            DB::commit();
            return $this->returnApi(200, '删除成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '删除失败');
        }
    }

    /**
     * 展览 添加 作品
     * @param id 展览id
     * @param production_id 作品id （只传添加的） 多个 逗号 分隔  
     */
    public function exhibitionAddProduction()
    {
        //增加验证场景进行验证
        if (!$this->validateObj->scene('exhibition_add_production')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validateObj->getError());
        }

        $production_id = $this->request->production_id;

        $res = $this->exhibitionModelObj->where('is_del', 1)->find($this->request->id);
        if (empty($res)) {
            return $this->returnApi(202, '添加失败');
        }

        DB::beginTransaction();
        try {
            $exhibitionProductionModelObj = new ExhibitionProduction();
            $exhibitionProductionModelObj->exhibitionProductionAdd($this->request->id, $production_id);

            DB::commit();
            return $this->returnApi(200, '添加成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '添加失败');
        }
    }

    /**
     * 展览 配置 机柜
     * @param id 展览id
     * @param bookcase_id 作品id （所有的机柜id） 多个 逗号 分隔   空表示清空 书柜
     */
    public function exhibitionConfigBookcase()
    {
        //增加验证场景进行验证
        if (!$this->validateObj->scene('exhibition_config_bookcase')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validateObj->getError());
        }

        $bookcase_id = $this->request->bookcase_id;

        $res = $this->exhibitionModelObj->where('is_del', 1)->find($this->request->id);
        if (empty($res)) {
            return $this->returnApi(202, '配置失败');
        }

        DB::beginTransaction();
        try {
            $bookcaseExhibitionModelObj = new BookcaseExhibition();
            $bookcaseExhibitionModelObj->exhibitionBookcaseChange($res->id, $bookcase_id,'change');

              //修改机柜配置展览信息
              $bookcaseModelObj = new Bookcase();
              $bookcase_id_arr = explode(',', $bookcase_id);
              foreach ($bookcase_id_arr as $key => $val) {
                  $bookcaseModelObj->isConfigChange($val);
              }

            DB::commit();
            return $this->returnApi(200, '配置成功', true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, '配置失败');
        }
    }

    /**
     * 展览添加
     * @param name 展览名称    必选
     * @param type_name 展览名称  必选
     * @param address 展览地址     必选
     * @param start_time 展览开始时间
     * @param end_time 展览结束时间
     * @param opening_time 开幕时间
     * @param roll_speed  前言文字滚动速率    指文字 或图片滚动完一个屏幕所需时间
     * @param page_stay_min_time 页面停留的最短时间 单位秒，和滚动时间比较，取最大值
     * @param sponsor 主办单位
     * @param undertaker 承办单位
     * @param special_thanks 特别呜谢
     * @param academic_host 学术主持
     * @param chief_inspector 总监
     * @param curator 策展人
     * @param intro 简介
     * @param fore_id 前言id
     * @param production_id 作品id （所有的展览id） 多个 逗号 分隔    与 fore_id 可以2选一，可以同时存在，但不能同时不存在
     * @param bookcase_id 机柜id （所有的机柜id） 多个 逗号 分隔  可为空
     */

    public function exhibitionAdd()
    {
        //增加验证场景进行验证
        if (!$this->validateObj->scene('exhibition_add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validateObj->getError());
        }

        $fore_id = $this->request->fore_id;
        $production_id = $this->request->production_id;
        $bookcase_id = $this->request->bookcase_id;
        if (empty($fore_id) && empty($production_id)) {
            return $this->returnApi(202, '前言和作品必须选择一个');
        }

        $is_exists = $this->exhibitionModelObj->exhibitionNameIsExists($this->request->name);
        if ($is_exists) {
            return $this->returnApi(202, '此名称已存在，请重新添加');
        }

        DB::beginTransaction();
        try {

            $res = $this->exhibitionModelObj->add($this->request);
            //添加作品
            if (!empty($production_id)) {
                $exhibitionProductionModelObj = new ExhibitionProduction();
                $exhibitionProductionModelObj->exhibitionProductionChange($this->exhibitionModelObj->id, $production_id, 'add');
            }
            //添加书柜
            if (!empty($bookcase_id)) {
                $bookcaseExhibitionModelObj = new BookcaseExhibition();
                $bookcaseExhibitionModelObj->exhibitionBookcaseChange($this->exhibitionModelObj->id, $bookcase_id,'add');

                //修改机柜配置展览信息
                $bookcaseModelObj = new Bookcase();
                $bookcase_id_arr = explode(',', $bookcase_id);
                foreach ($bookcase_id_arr as $key => $val) {
                    $bookcaseModelObj->isConfigChange($val);
                }
            }

            DB::commit();
            return $this->returnApi(200, '添加成功', true);
        } catch (\Exception $e) {
            //   echo $e->getMessage();die;
            DB::rollBack();
            return $this->returnApi(202, '添加失败');
        }
    }

    /**
     * 展览修改
     * @param id  展览id  必选
     * @param name 展览名称    必选
     * @param type_name 展览名称  必选
     * @param address 展览地址     必选
     * @param start_time 展览开始时间
     * @param end_time 展览结束时间
     * @param opening_time 开幕时间
     * @param roll_speed  前言文字滚动速率    指文字 或图片滚动完一个屏幕所需时间
     * @param page_stay_min_time 页面停留的最短时间 单位秒，和滚动时间比较，取最大值
     * @param sponsor 主办单位
     * @param undertaker 承办单位
     * @param special_thanks 特别呜谢
     * @param academic_host 学术主持
     * @param chief_inspector 总监
     * @param curator 策展人
     * @param intro 简介
     * @param fore_id 前言id
     * @param production_id 作品id （所有的展览id） 多个 逗号 分隔    与 fore_id 可以2选一，可以同时存在，但不能同时不存在
     * @param bookcase_id 机柜id （所有的机柜id） 多个 逗号 分隔  可为空
     */

    public function exhibitionChange()
    {
        //增加验证场景进行验证
        if (!$this->validateObj->scene('exhibition_change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validateObj->getError());
        }
        $fore_id = $this->request->fore_id;
        $production_id = $this->request->production_id;
        $bookcase_id = $this->request->bookcase_id;

        if (empty($fore_id) && empty($production_id)) {
            return $this->returnApi(202, '前言和作品必须选择一个');
        }

        $res = $this->exhibitionModelObj->where('is_del', 1)->find($this->request->id);
        if (empty($res)) {
            return $this->returnApi(202, '获取失败');
        }
        if($res->status == 1){
            return $this->returnApi(202, '此展览正在展示中，禁止修改');
        }

        $is_exists = $this->exhibitionModelObj->exhibitionNameIsExists($this->request->name, $this->request->id);
        if ($is_exists) {
            return $this->returnApi(202, '此名称已存在，请重新修改');
        }

        DB::beginTransaction();
        try {

            $this->exhibitionModelObj->change($this->request);
            //修改作品
            $exhibitionProductionModelObj = new ExhibitionProduction();
            $exhibitionProductionModelObj->exhibitionProductionChange($this->request->id, $production_id, 'change');

            //修改书柜
            $bookcaseExhibitionModelObj = new BookcaseExhibition();
         

            //修改机柜配置展览信息
            $bookcase_id_all = $bookcaseExhibitionModelObj->getBookcaseIdByExhibitionId($this->request->id);//获取所有的机柜
            $bookcaseModelObj = new Bookcase();

            $bookcase_id_arr = $bookcase_id ? explode(',' , $bookcase_id) : [];
            $bookcase_id_arr = array_unique(array_merge($bookcase_id_all , $bookcase_id_arr));

            foreach ($bookcase_id_arr as $key => $val) {
                $bookcaseModelObj->isConfigChange($val);
            }

            $bookcaseExhibitionModelObj->exhibitionBookcaseChange($this->request->id, $bookcase_id,'change');

            DB::commit();
            return $this->returnApi(200, '修改成功', true);
        } catch (\Exception $e) {
          //  echo $e->getMessage();die;
            DB::rollBack();
            return $this->returnApi(202, '修改失败');
        }
    }

    /**
     * 展览显示与关闭
     * @param id  展览id  必选
     * @param status 状态  1 显示  2 未显示
     */

    public function statusChange()
    {
         //增加验证场景进行验证
         if (!$this->validateObj->scene('status_change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validateObj->getError());
        }
        $res = $this->exhibitionModelObj->where('is_del', 1)->find($this->request->id);
        if (empty($res)) {
            return $this->returnApi(202, '获取失败');
        }
        $res->status = $this->request->status;
        $result = $res->save();

        if ($result) {
            return $this->returnApi(200, '修改成功', true);
        }

        return $this->returnApi(202, '修改失败');

    }
    /**
     * 展览删除
     * @param id  展览id  必选
     */

    public function exhibitionDel()
    {
        //增加验证场景进行验证
        if (!$this->validateObj->scene('exhibition_del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validateObj->getError());
        }
        //判断展览是否有展览
        $bookcaseExhibition = new BookcaseExhibition();
        $is_bookcase = $bookcaseExhibition->exhibitionIsBookcase($this->request->id);
        if ($is_bookcase) {
            return $this->returnApi(202, '此展览正在机柜《' . $is_bookcase . '》中展览，请先取消后在进行删除');
        }

        $res = $this->exhibitionModelObj->where('is_del', 1)->find($this->request->id);
        if (empty($res)) {
            return $this->returnApi(202, '删除失败');
        }
        if($res->status == 1){
            return $this->returnApi(202, '此展览正在展示中，禁止删除');
        }
        $res->is_del = 2;
        $result = $res->save();

        if ($result) {
            return $this->returnApi(200, '删除成功', true);
        }

        return $this->returnApi(202, '删除失败');
    }
}
